package com.example.webjsdemo

import android.app.Service
import android.content.Context
import android.media.AudioManager
import android.media.MediaPlayer
import android.media.RingtoneManager
import android.net.Uri
import android.os.Build
import android.os.VibrationEffect
import android.os.Vibrator
import android.webkit.JavascriptInterface
import androidx.annotation.RequiresApi

/**
 * author: tdq
 * date: #date
 * description:
 */
class AndroidJs(private val mContext: Context) {

    private val vibrator = mContext.getSystemService(Service.VIBRATOR_SERVICE) as Vibrator

    private var mMediaPlayer: MediaPlayer? = null

    @RequiresApi(Build.VERSION_CODES.O)
    @JavascriptInterface
    fun startVibratorFunction() {
        vibrator.vibrate(VibrationEffect.createWaveform(longArrayOf(1000, 2000, 500, 0), 0))
    }

    @RequiresApi(Build.VERSION_CODES.O)
    @JavascriptInterface
    fun cancelVibratorFunction() {
        vibrator.cancel()
    }

    //开始播放
    @JavascriptInterface
    fun startRingFunction() {
        try {
            //用于获取手机默认铃声的Uri
            val alert: Uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE)
            mMediaPlayer = MediaPlayer()
            mMediaPlayer?.setDataSource(mContext, alert)
            //告诉mediaPlayer播放的是铃声流
            mMediaPlayer?.setAudioStreamType(AudioManager.STREAM_RING)
            mMediaPlayer?.isLooping = true
            mMediaPlayer?.prepare()
            mMediaPlayer?.start()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    //停止播放
    @JavascriptInterface
    fun stopRingFunction() {
        if (mMediaPlayer != null) {
            if (mMediaPlayer?.isPlaying == true) {
                mMediaPlayer?.stop()
                mMediaPlayer?.release()
            }
        }
    }

    @RequiresApi(Build.VERSION_CODES.O)
    @JavascriptInterface
    fun stopVibratorAndRingFunction() {
        cancelVibratorFunction()
        stopRingFunction()
    }
}